package com.orange.cetback.service.impl;

import com.orange.cetback.common.utils.SiliconFlowUtil;
import com.orange.cetback.pojo.dto.SiliconChatDTO;
import com.orange.cetback.pojo.vo.ChatVO;
import com.orange.cetback.pojo.vo.SiliconChatResponse;
import com.orange.cetback.service.SiliconFlowService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.nio.charset.StandardCharsets;

@Service
public class SiliconFlowServiceImpl implements SiliconFlowService {

    @Autowired
    private SiliconFlowUtil siliconFlowUtil;

    @Autowired
    private WebClient webClient;


    @Override
    public ChatVO handleChatRequest(SiliconChatDTO dto) {
        SiliconChatResponse response = siliconFlowUtil.chatCompletion(dto);
        ChatVO  chatVO = new ChatVO();
        BeanUtils.copyProperties(response.getChoices().get(0).getMessage(),chatVO);
        return chatVO;
    }



    public Flux<String> streamFromThirdParty() {
        return webClient.get()
                .uri("/v1/chat/completions") // 第三方API流式端点
                .retrieve()
                .bodyToFlux(DataBuffer.class)
                .map(dataBuffer -> {
                    // 将DataBuffer转换为字符串（根据实际编码调整）
                    byte[] bytes = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(bytes);
                    DataBufferUtils.release(dataBuffer);
                    return new String(bytes, StandardCharsets.UTF_8);
                })
                .onErrorResume(e -> {
                    // 错误处理逻辑
                    return Flux.error(new RuntimeException("API调用失败", e));
                });
    }
}
